# uninstall-office.ps1
# Removes Click-to-Run Office products using the Office Deployment Tool.
# This script is intended to run as a FileWave pre-uninstallation script
# when the Office Fileset association is removed.

$OfficeRoot = "C:\ProgramData\FileWave\Installers\Office"
$SetupExe = Join-Path $OfficeRoot "setup.exe"
$RemoveXml = Join-Path $OfficeRoot "remove-office.xml"
$LogRoot = "C:\ProgramData\FileWave\Logs"
$LogFile = Join-Path $LogRoot "office-uninstall.log"

if (-not (Test-Path $LogRoot)) {
    New-Item -Path $LogRoot -ItemType Directory -Force | Out-Null
}

function Write-Log {
    param (
        [string]$Message
    )

    $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$Timestamp $Message" | Tee-Object -FilePath $LogFile -Append
}

Write-Log "Starting Microsoft Office removal."

if (-not (Test-Path $SetupExe)) {
    Write-Log "ERROR: setup.exe not found at $SetupExe"
    exit 1
}

# Remove all Click-to-Run Office products installed by ODT, including Office, Project, and Visio.
# Use a more targeted Remove XML if you only want to remove a specific product.
$RemoveXmlContent = @"
<Configuration>
  <Remove All="TRUE" />
  <Display Level="None" AcceptEULA="TRUE" />
</Configuration>
"@

$RemoveXmlContent | Out-File -FilePath $RemoveXml -Encoding utf8 -Force

try {
    $Process = Start-Process -FilePath $SetupExe `
        -ArgumentList "/configure `"$RemoveXml`"" `
        -Wait `
        -PassThru `
        -WindowStyle Hidden

    Write-Log "Office Deployment Tool exited with code $($Process.ExitCode)."

    if ($Process.ExitCode -ne 0) {
        Write-Log "ERROR: Office removal failed."
        exit $Process.ExitCode
    }

    Write-Log "Microsoft Office removal completed successfully."
    exit 0
}
catch {
    Write-Log "ERROR: $($_.Exception.Message)"
    exit 1
}